package com.tanhua.server.interceptors;

import com.tanhua.domain.db.User;
import com.tanhua.server.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Autowired
    private UserService  userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

//        要获取token 根据token获取user
        String token = request.getHeader("Authorization");

        if(StringUtils.isBlank(token)){
            return false; // 拦截
        }
        User user = userService.getUserByToken(token);
        UserHolder.setUser(user);
        return true;// 放行
    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserHolder.removeFromThreadLocal();
    }
}
